package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.itheima.dao.OrderSettingDao;
import com.itheima.pojo.OrderSetting;
import com.itheima.service.OrderSettingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service(interfaceClass = OrderSettingService.class)
@Transactional
public class OrderSettingServiceImpl implements OrderSettingService {

    @Autowired
    private OrderSettingDao orderSettingDao;

    @Override
    public void upload(List<OrderSetting> orderSettings) {
        if (orderSettings != null && orderSettings.size() > 0){
            for (OrderSetting orderSetting : orderSettings) {
                //判断当前日期是否已经进行预约设置
                Date orderDate = orderSetting.getOrderDate();
                Long count = orderSettingDao.findCountByOrderDate(orderDate);
                if (count > 0){
                    //1)若已经进行预约,执行[更新]操作
                    orderSettingDao.updateByOrderDate(orderSetting);
                }else {
                    //2)否则执行[插入]操作
                    orderSettingDao.insertByOrderDate(orderSetting);
                }
            }
        }
    }

    @Override
    public List<Map> getOrderSettingByYearAndMonth(String date) {
        //通过年、月查找一整个月中的[orderSetting]
        //Map格式 :  { date: 1, number: 120, reservations: 1 }
        List<OrderSetting> orderSettings = orderSettingDao.getOrderSettingByYearAndMonth(date);
        List<Map> maps = new ArrayList<>();
        if (orderSettings != null && orderSettings.size() > 0){
            for (OrderSetting orderSetting : orderSettings) {
                Map map = new HashMap();
                //获取日期
                int orderDate = orderSetting.getOrderDate().getDate();
                int number = orderSetting.getNumber();
                int reservations = orderSetting.getReservations();
                map.put("date",orderDate);
                map.put("number",number);
                map.put("reservations",reservations);
                maps.add(map);
            }
        }
        return maps;
    }

    @Override
    public void updateOrderSettingNumberByInput(OrderSetting orderSetting) {
        //数据库中是否存在该[日期]对应的条目,有则更新,无则插入
        Long count = orderSettingDao.findCountByOrderDate(orderSetting.getOrderDate());
        if (count > 0){
            //1)更新
            orderSettingDao.updateByOrderDate(orderSetting);
        }else {
            //2)插入
            orderSettingDao.insertByOrderDate(orderSetting);
        }
    }
}
